#ifdef WIN32
#include <atlstr.h>
#endif
#include "TrueText/Config.h"
#include "ftutils.h"

#include <assert.h>

void truetext_lib_assert(const char * _Message, const char *_File, unsigned _Line)
{
	#ifdef WIN32
	#ifdef DEBUG
		_wassert(CA2W(_Message), CA2W(_File), _Line);
	#endif
	#else
		assert(_Message);
	#endif
}

struct FT_Error_DescriptionW
{
		int          err_code;
		const wchar_t*  err_msg;
};

struct FT_Error_DescriptionA
{
		int          err_code;
		const char*  err_msg;
};

std::string LookupFreeTypeErrorMessageA(FT_Error error)
{
	#undef __FTERRORS_H__
	#define FT_ERRORDEF( e, v, s )  { e, s },
	#define FT_ERROR_START_LIST     {
	#define FT_ERROR_END_LIST       { 0, 0 } };

	FT_Error_DescriptionA ft_errors[] =
	#include FT_ERRORS_H


	for (FT_Error_DescriptionA* currentDescription = ft_errors;
		currentDescription->err_code || currentDescription->err_msg;
		++currentDescription)
	{
		if (currentDescription->err_code == error)
			return currentDescription->err_msg;
	}

	return "Unknown error";
}

std::wstring LookupFreeTypeErrorMessageW(FT_Error error)
{
	#undef __FTERRORS_H__
	#define FT_ERRORDEF( e, v, s )  { e, L##s },
	#define FT_ERROR_START_LIST     {
	#define FT_ERROR_END_LIST       { 0, 0 } };

	FT_Error_DescriptionW ft_errors[] =
	#include FT_ERRORS_H

	
	for (FT_Error_DescriptionW* currentDescription = ft_errors;
		currentDescription->err_code || currentDescription->err_msg;
		++currentDescription)
	{
		if (currentDescription->err_code == error)
			return currentDescription->err_msg;
	}

	return L"Unknown error";
}

FT_Library g_freeTypeLibrary;

void InitLibraryHandle()
{
	FT_EH(FT_Init_FreeType(&g_freeTypeLibrary));
}

void CloseLibraryHandle()
{
	FT_Done_FreeType(g_freeTypeLibrary);
	g_freeTypeLibrary = 0;
}

FT_Library GetLibraryHandle()
{
	return g_freeTypeLibrary;
}

#ifdef ANDROID_NDK
#include <android/log.h>

void TrueText_Android_Log(char* msg)
{
	__android_log_print(ANDROID_LOG_ERROR, "TrueText", msg);
}
#endif

#ifndef MARMALADE
#pragma comment (lib, "freetype.lib")
#endif